//
//  HAODE
//
//  Created by panquanReabam.com on 15/9/23.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "WhsInAddViewController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "UIImageView+WebCache.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "GoodsView.h"
#import "WhsInListViewController.h"
#import "WhsOutListViewController.h"
#import "WhsWhsItemListViewController.h"
#import "OptionNameListViewController.h"
#import "CheckVouchListViewController.h"

#import "WhsInAddView.h"
#import "WhsInAddModel.h"
#import "PlatformProductTypeListViewController.h"
@interface WhsInAddViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UISearchBarDelegate,UIScrollViewDelegate,WhsInAddViewDelegate,OptionNameListViewControllerDelegate,WhsWhsItemListViewControllerDelegate,PlatformProductTypeListViewControllerDelegate>
@property (strong, nonatomic) NSString*whsInTypeCode;
@property (strong, nonatomic) NSString*whsId;
@property (strong, nonatomic) NSString*WhsInType;
@end

@implementation WhsInAddViewController
{
    WhsInAddView*AddView;
    UIScrollView*MYmainScroll;
    NSString *userToken;
}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];

    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    //会员信息
    self.title = self.titleName;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    

}
-(void)checkVouchType:(NSString *)checkVouchType checkVouchTypeCode:(NSString *)checkVouchTypeCode{

    self.whsInTypeCode=checkVouchTypeCode;
    [AddView.typeBtn setTitle:checkVouchType forState:UIControlStateNormal];

}
- (void)ExpressCompany:(NSString *)ExpressCompany ExpressCompanyCode:(NSString *)ExpressCompanyCode{}
-(void)Whs:(NSString *)Whs WhsCode:(NSString *)WhsCode{

    self.whsId=WhsCode;
    [AddView.whsBtn setTitle:Whs forState:UIControlStateNormal];

}
-(void)WhsInType:(NSString *)WhsInType WhsInTypeCode:(NSString *)WhsInTypeCode{

        self.whsInTypeCode=WhsInTypeCode;
       [AddView.typeBtn setTitle:WhsInType forState:UIControlStateNormal];

}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    MYmainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight)];
    [MYmainScroll setBackgroundColor: zuiqianhuiColor];
    MYmainScroll.delegate = self;
    MYmainScroll.userInteractionEnabled = YES;
    MYmainScroll.scrollEnabled = YES;
    MYmainScroll.showsVerticalScrollIndicator = FALSE;
    MYmainScroll.showsHorizontalScrollIndicator = FALSE;
    [self.view addSubview:MYmainScroll];
    AddView=[[WhsInAddView alloc]init];
    AddView.mDelegate=self;
    AddView.specNameArray=self.specNameArray;
    AddView.itemCodeArray=self.itemCodeArray;
    AddView.itemNameArray=self.itemNameArray;
    AddView.specIdArray=self.specIdArray;
    AddView.dealPriceArray=self.dealPriceArray;
    AddView.quantityArray=self.quantityArray;
    AddView.headImageFullArray=self.headImageFullArray;
    WhsInAddModel *dataModel=[WhsInAddModel dataModelWithWhsInAddtDict:@""];
    AddView.model=dataModel;
    AddView.frame=CGRectMake(0, 0, ScreenWidth, AddView.heightView.bottom);
    [MYmainScroll addSubview:AddView];
    MYmainScroll.contentSize = CGSizeMake(ScreenWidth, AddView.bottom+100);
    [self addbuyBtn];
    
    
}
//盘点 入库 出库
-(void)shouying:(UIButton *)sender {
    if ([AddView.typeBtn.titleLabel.text length] < 1) {
        [self showAlertMessage:@"请选择类型！"];
    } else{
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:userToken forKey:@"tokenId"];
            [params setValue:self.whsId forKey:@"whsId"];
    if ([self.Whs isEqualToString:@"WhsOut"]) {
        [params setValue:self.whsInTypeCode forKey:@"whsOutTypeCode"];
        }
         if ([self.Whs isEqualToString:@"WhsOut"]) {
        [params setValue:self.whsInTypeCode forKey:@"whsInTypeCode"];
        
        }
        if ([self.Whs isEqualToString:@"CheckVouch"]) {
            [params setValue:self.whsInTypeCode forKey:@"itemTypeCode"];
            [params setValue:AddView.typeBtn.titleLabel.text forKey:@"itemTypeName"];
            
        }
        
            NSMutableArray *mDocumentLine=[NSMutableArray array];
        for (int i=0; i<self.specIdArray.count; i++) {
        
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSString *itemId = [self.itemIdArray objectAtIndex:i];
                NSString *quantity =[self.quantityArray objectAtIndex:i];
                NSString *specId =[NSString stringWithFormat:@"%@",[self.specIdArray objectAtIndex:i]];
                
                
                [dic setValue:quantity forKey:@"quantity"];
                [dic setValue:itemId forKey:@"itemId"];
                if ([specId isEqualToString:@""]) {
                    
                }else{
                   
                    if ([specId isEqualToString:@"<null>"]) {
                        specId=@"";
                    }
                    [dic setValue:specId forKey:@"specId"];
                }
               
                [mDocumentLine addObject:dic];
        
        
            }
    
            [params setValue:mDocumentLine  forKey:@"itemList"];
            [params setValue:AddView.remark.text  forKey:@"remark"];
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:[NSString stringWithFormat:@"Business/%@/Add",self.Whs] params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
         
//                        [ClearFB clearUserData:userToken typeString:_saveTypeStr];
                        if ([self.Whs isEqualToString:@"CheckVouc"]) {
                            CheckVouchListViewController *detailViewController = [[CheckVouchListViewController alloc] init];
                            [self.navigationController pushViewController:detailViewController animated:YES];}
                        
                        if ([self.Whs isEqualToString:@"WhsOut"]) {
                            WhsOutListViewController *detailViewController = [[WhsOutListViewController alloc] init];
                            [self.navigationController pushViewController:detailViewController animated:YES];
                        }

                        if ([self.Whs isEqualToString:@"WhsIn"]) {
                            WhsInListViewController *detailViewController = [[WhsInListViewController alloc] init];
                            [self.navigationController pushViewController:detailViewController animated:YES];
                        }
                     }else{
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }}
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:@"连接失败 这条数据在维护！" view:self.view];
                }
                
            }];
   
    }
}

-(void)whs:(NSString *)whs{
    WhsWhsItemListViewController *detailViewController = [[WhsWhsItemListViewController alloc] init];
    detailViewController.mDelegate=self;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

-(void)type:(NSString *)type{

   
      if ([self.Whs isEqualToString:@"CheckVouc"]) {
          PlatformProductTypeListViewController *detailViewController = [[PlatformProductTypeListViewController alloc] init];
          [self.navigationController pushViewController:detailViewController animated:YES];}else{
          
              OptionNameListViewController *detailViewController = [[OptionNameListViewController alloc] init];
              detailViewController.optionName=self.Type;
              detailViewController.titlename=@"选择类型";
              detailViewController.mDelegate=self;
              [self.navigationController pushViewController:detailViewController animated:YES];

          
          }
}

- (void)BeginEditing:(NSString *)BeginEditing{
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    MYmainScroll .frame =CGRectMake(0, -100, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];

}

-(void)OnTapDone:(NSString *)OnTapDone {
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    MYmainScroll .frame =CGRectMake(0,0, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];

}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)addbuyBtn{
    
    NSMutableArray*  sum=[[NSMutableArray alloc]init];
    
    for (int i=0; i<self.dealPriceArray.count; i++) {
        NSString *typeCode1 = [self.dealPriceArray objectAtIndex:i];
        NSString *isSingle1 = [self.quantityArray objectAtIndex:i];
        [sum addObject:[NSString stringWithFormat:@"%.2f",  [typeCode1 doubleValue]*[isSingle1 doubleValue]]];
    }
    
    NSNumber *sum11 = [sum valueForKeyPath:@"@sum.floatValue"];
    NSString*GoldPrice=[NSString stringWithFormat:@"%@",sum11];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:GoldPrice.floatValue]];
    UIButton*totalQuantity=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48, ScreenWidth*430/750, 45)];
    [totalQuantity setTitle:[NSString stringWithFormat:@"   合计 ¥ %@",formattedNumberString] forState:UIControlStateNormal];
    totalQuantity.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
    [totalQuantity setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    totalQuantity.alpha=0.8;
    totalQuantity.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    totalQuantity.contentVerticalAlignment=UIControlContentVerticalAlignmentBottom;
    totalQuantity.titleLabel.font=[UIFont systemFontOfSize:18];
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"   合计 ¥ %@",formattedNumberString]];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:13]
     
                          range:NSMakeRange(0, 7)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:[UIColor whiteColor]
     
                          range:NSMakeRange(0, 7)];
    
    
    totalQuantity.titleLabel.attributedText = AttributedStr;
    
    UIButton* quantityBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 9, ScreenWidth*430/750, 11)];
    NSNumber *sum1 = [self.quantityArray valueForKeyPath:@"@sum.floatValue"];
    [quantityBtn setTitle:[NSString stringWithFormat:@"   共 %@ 件商品",sum1] forState:UIControlStateNormal];
    quantityBtn.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
    [quantityBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    quantityBtn.titleLabel.font=[UIFont systemFontOfSize:11];
    quantityBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    [totalQuantity addSubview:quantityBtn];
    [self.view addSubview:totalQuantity];
    UIButton*dise=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-3, ScreenWidth*430/750, 3)];
    dise.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
    [self.view addSubview:dise];
    UIButton*buyBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth*430/750, ScreenHeight-48, ScreenWidth*320/750, 48)];
    [buyBtn setTitle:@"确定" forState:UIControlStateNormal];
    buyBtn.backgroundColor=luseColor;
    [buyBtn addTarget:self action:@selector(shouying:) forControlEvents:UIControlEventTouchUpInside];
    [buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:buyBtn];
    
}


@end
